import re
from rest_framework import serializers

from users.utlis import get_verify_url
from .models import Users
from django_redis import get_redis_connection
from .models import Address

class RegisterCreateUserSerializer(serializers.ModelSerializer):


    # 用户名, 密码, 确认密码, 手机号, 短信验证码, 是否同意协议
    # 确认密码　模型中没有　我们需要手动添加
    # write_only=True 表示只在反序列化的时候　使用这个字段
    #                       在序列化(将模型转换为JSON)时忽略此字段

    password2 = serializers.CharField(label="确认密码",min_length=8,max_length=20,write_only=True)
    sms_code = serializers.CharField(label='短信验证码',max_length=6,min_length=6,write_only=True)
    allow = serializers.CharField(label='是否同意协议',allow_blank=False,write_only=True)

    token = serializers.CharField(label="token",read_only=True)
    # token只是应用于在　序列化(对象转换为JSON)操作的时候使用

    class Meta:
        model = Users
        fields = ['username','password','mobile','password2','sms_code','allow',"token"]

        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    """
    1.字段类型的验证
    2.字段选项的验证
    3.单个字段的验证
    4.多个字段的验证
    """

    # 用户名, 密码, 确认密码, 手机号, 短信验证码, 是否同意协议

    def validate_mobile(self, value):
        if not re.match('1[3-9]\d{9}',value):
            raise serializers.ValidationError("手机号不符合格式")

        return value

    def validate_allow(self,value):
        if value != "true":
            raise serializers.ValidationError("请同意协议")

        return value


    def validate(self, attrs):
        # 1.确认密码
        password = attrs.get("password")
        password2 = attrs.get('password2')
        if password != password2:
            raise serializers.ValidationError("密码不一致")

        # 2.短信验证码
        redis_conn = get_redis_connection('code')

        redis_code = redis_conn.get('sms_%s'%attrs['mobile'])

        # 有时效
        if redis_code is None:
            raise serializers.ValidationError("验证码已过期")

        if redis_code.decode() != attrs['sms_code']:
            raise serializers.ValidationError('验证码不一致')

        return attrs



    def create(self, validated_data):

        print(validated_data)
        #　多余的字段删除
        del validated_data['sms_code']
        del validated_data['password2']
        del validated_data['allow']
        user = super().create(validated_data)
        # user = Users.objects.create(**validated_data)
        # print(user)
        # 修改密码
        user.set_password(validated_data['password'])
        user.save()

        # 生成一个token()

        # 如何生成token的几行代码
        from rest_framework_jwt.settings import api_settings
        # 我们需要获取　2个方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 1.jwt_payload_handler 我们需要将用户的信息传递给这个函数,函数自己或获取user中的数据
        # 获取了之后,会生成一个二进制
        payload = jwt_payload_handler(user)
        # 2.需要对payload　进行编码　编码之后才是token
        token = jwt_encode_handler(payload)

        user.token = token

        return user



class UserCenterInfoView(serializers.ModelSerializer):

    """
    用户详细信息序列化器
    """

    class Meta:
        model = Users
        fields = ('id','username','mobile','email','email_active')


# 邮件的序列化器
class UserUpdateEmaiserializer(serializers.ModelSerializer):
    """
    邮件序列化器
    """
    class Meta:
        model = Users
        fields = ('id','email')
        extra_kwargs={
            'email':{
                'required':True
            }

        }


    def update(self, instance, validated_data):
        print(instance)
        print(validated_data)

        #instance   -->更新的时候 传递过来的对象
        #validated_data  -->验证之后的数据

        # 调用父类的方法
        # super().update(instance,validated_data)

        instance.email = validated_data.get('email')
        instance.save()
        # 更新数据完成

        # 发送激活邮件
        from django.core.mail import send_mail

        # subject, message, from_email, recipient_list

        subject= '美多商城激活邮件'

        # 内容
        message= ''
        from mall.settings import EMAIL_FROM
        from_email= EMAIL_FROM


        # recipient_list='收件人列表'

        email = validated_data.get('email')
        recipient_list=[email]

        # url的内容 炫耀进行处理,而且需要有一定的时效
        verify_url = get_verify_url(instance.id,email)

        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)

        # send_mail(subject, message, from_email, recipient_list,html_message=html_message)


        # 消息中心()
        from celery_tasks.email.tasks import send_celery_email

        send_celery_email.delay(subject, message, from_email, recipient_list,html_message=html_message)


        return instance



"""增加地址的序列化器"""
class AddressSerializer(serializers.ModelSerializer):

    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:

        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def create(self, validated_data):

        # 新增数据的时候,设置user

        # validated_data['user'] = self.context['request'].user
        validated_data['user']=self.context['request'].user
        return Address.objects.create(**validated_data)

        # super().create(validated_data)



